package cn.itcast.dao;

import cn.itcast.Role;
import cn.itcast.UserInfo;
import org.apache.ibatis.annotations.*;


import java.util.List;

public interface UserDao {


    /**
     * 根据用户名查找数据库中的user对象
     * @param username
     * @return
     */
    @Select("select * from users where username = #{username}")
    @Results({
            @Result(id = true,property = "id",column = "id"),
            @Result(property = "username", column = "username"),
            @Result(property = "email", column = "email"),
            @Result(property = "password", column = "password"),
            @Result(property = "phoneNum", column = "phoneNum"),
            @Result(property = "status", column = "status"),
            @Result(property = "roles", column = "id",javaType = java.util.List.class,
                    many = @Many(select = "cn.itcast.dao.RoleDao.findRoleByUserId")),
    })
    UserInfo findByUsername(String username) throws Exception;

    /**
     * 查询所有的方法
     * @return
     */
    @Select("select * from users")
    List<UserInfo> findAll() throws Exception;

    /**
     * 添加用户
     * @param userInfo
     */
    //@Insert("insert into users(email,username,password,phoneNum,status) values(#{email},#{username},#{password},#{phoneNum},#{status})")
    @Insert("insert into users (email,username,password,phoneNum,status) values(#{email},#{username},#{password},#{phoneNum},#{status})")
    void save(UserInfo userInfo) throws Exception;

    /**
     * 根据id查询用户并查询关联的角色表
     * @param id
     * @return
     */
    @Select("select * from users where id = #{id}")
    @Results({
            @Result(id = true,property = "id",column = "id"),
            @Result(property = "username", column = "username"),
            @Result(property = "email", column = "email"),
            @Result(property = "password", column = "password"),
            @Result(property = "phoneNum", column = "phoneNum"),
            @Result(property = "status", column = "status"),
            @Result(property = "roles", column = "id",javaType = java.util.List.class,
                    many = @Many(select = "cn.itcast.dao.RoleDao.findRoleByUserId"))
    })
    UserInfo findById(String id) throws Exception;

    /**
     * 给用户添加角色
     * @param userId
     * @param roleId
     */
    @Insert("insert into users_role (userId,roleId) values (#{userId},#{roleId})")
    void addRoleToUser(@Param("userId") String userId, @Param("roleId") String roleId);


    /**
     * 根据userId删除users_role中外键
     * @param userId
     * @throws Exception
     */
    @Delete("delete from users_role where userId = #{userId}")
    void delURByUserId(String userId) throws Exception;

    /**
     * 根据userId删除users中的user
     * @param userId
     */
    @Delete("delete from users where id = #{userId}")
    void delUserByUserId(String userId) throws Exception;
}
